package com.v1.video.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.MediaController;
import android.widget.VideoView;

import com.v1.video.R;

public class VideoViewActivity extends Activity {

	private VideoView mVideoView;
	private ProgressDialog mpd;
	private boolean isPlay = false;
	private int mPosition = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_videoview);
		initView();
		setListener();
		initData();
	}
	

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (mVideoView != null) {
			mVideoView.resume();
			if (isPlay == true) {
				mVideoView.seekTo(mPosition);
				mVideoView.start();
			}
		}
	}


	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mVideoView != null) {
			if (mVideoView.isPlaying()) {
				isPlay = true;
			} else {
				isPlay = false;
			}
			mPosition = mVideoView.getCurrentPosition();
			mVideoView.pause();
		}
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		release();
		if (mVideoView != null) {
			mVideoView.stopPlayback();
		}
	}



	protected void initView() {
		// TODO Auto-generated method stub
		mVideoView = (VideoView) this.findViewById(R.id.vv_videoView);
	}
	
	protected void setListener() {
		// TODO Auto-generated method stub
		mVideoView.setOnPreparedListener(new OnPreparedListener() {
			
			@Override
			public void onPrepared(MediaPlayer mp) {
				// TODO Auto-generated method stub
				release();
			}
		});
		
		this.findViewById(R.id.iv_result).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				VideoViewActivity.this.finish();
			}
		});
	}

	protected void initData() {
		// TODO Auto-generated method stub
		String url = this.getIntent().getStringExtra("url");
		Uri uri = Uri.parse(url);
		mVideoView.setVideoURI(uri);
		mVideoView.setMediaController(new MediaController(this));
		mVideoView.requestFocus();
		mVideoView.start();
		mpd = new ProgressDialog(this);
		mpd.setMessage("加载中视频...");
		mpd.show();
	}

	
	
	private void release() {
		if (mpd != null) {
			if (mpd.isShowing()) {
				mpd.dismiss();
			}
			mpd = null;
		}
	}

}
